package org.example.sword2offer.primary;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author: lynn
 * @Descript:   LeetCode.102. 二叉树的层序遍历
 * @date: 2021/6/29 21:51
 * @version: 1.0
 */
public class Q76_PrintDepTreeNode {

    public static void main(String[] args) {
        TreeNode treeNode=new TreeNode(5);
        treeNode.leftNode=new TreeNode(3);
        treeNode.rightNode=new TreeNode(7);
        treeNode.leftNode.leftNode=new TreeNode(2);
        treeNode.leftNode.rightNode=new TreeNode(4);
        treeNode.rightNode.leftNode=new TreeNode(6);
        treeNode.rightNode.rightNode=new TreeNode(8);
        treeNode.rightNode.rightNode.leftNode=new TreeNode(9);
        treeNode.rightNode.rightNode.rightNode=new TreeNode(10);
        Q76_PrintDepTreeNode printDepTreeNode=new Q76_PrintDepTreeNode();
        System.out.println(printDepTreeNode.treeNodeOrderLevel(treeNode));
    }

    //解题答案: https://www.bilibili.com/video/BV1wz4y1C7Tm?from=search&seid=2878409353425606654
    public List<ArrayList<Integer>> treeNodeOrderLevel(TreeNode root) {
        List<ArrayList<Integer>> list = new ArrayList<>();
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while (q.size() != 0) {
            int size = q.size();
            ArrayList<Integer> tempList = new ArrayList<Integer>();
            for (int i = 0; i < size; i++) { //fixme 在for循环里面将q逐个取出来，是size，不是 q.size()
                TreeNode tmpNode = q.poll();
                tempList.add(tmpNode.val);
                if (tmpNode.leftNode != null) {
                    q.offer(tmpNode.leftNode);
                }
                if (tmpNode.rightNode != null) {
                    q.offer(tmpNode.rightNode);
                }
            }
            list.add(tempList);
        }
        return list;
    }
    private static class TreeNode{
        TreeNode leftNode;
        TreeNode rightNode;
        int val;
        TreeNode(int val){
            this.val=val;
        }
    }
}
